<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use DB;

class BrandController extends Controller
{
    /*
		添加品牌
    */
	public function getAdd()
	{
		//解析模板
		return view('admin.brand.add');
	}

	/*
		执行添加
	*/
	public function postInsert(Request $request)
	{
		
		$data =$request->except('_token');
		//添加折扣时间
		$data['btime'] = strtotime($data['btime']);

		//图片添加
		$data['bpic'] = UserController::upload($request,'bpic','brand');
		$data['regtime'] = time();
		//执行添加
		$res = DB::table('shop_brand')->insert($data);
		if($res){
			return redirect('/admin/brand/index')->with('success','添加成功');
		}else{
			return back()->with('error','添加失败');
		}
	}

	/*
		品牌列表
	*/
	public function getIndex(Request $request)
	{
		//获取每页显示条数
		$num = $request->input('num',10);
		
		//获取参数列表
		$list = $request->all();

		//判断是否有查询条件
		if($request->input('keywords')){
			$brand = DB::table('shop_brand')->where('bname','like','%'.$request->input('keywords').'%')->paginate($num);
		}else{
			$brand = DB::table('shop_brand')->paginate($num);
		}
		// $brand = DB::table('shop_brand')->get();
		
		
		// //解析模板
		return view('admin.brand.index',['brand'=>$brand,'list'=>$list,'num'=>$num]);
	} 

	/*
		品牌删除
	*/
	public function postDelete(Request $request)
	{
		//获取id
		$id = $request->input('id');

		//获取图片路径
		$path = DB::table("shop_brand")->where('bid',$id)->value('bpic');
		//删除数据库
		$res = DB::table('shop_brand')->where('bid',$id)->delete();
		//删除本地图片
		if(!empty($path)){
			$path = '.'.$path;
			if(file_exists($path)){
				unlink($path);
			}
		}
		//返回给ajax
		echo $res;
	}

	/*
		商品修改
	*/
	public function getEdit(Request $request)
	{
		
		$id = $request->input('id');
		//获取数据
		$brand = DB::table('shop_brand')->where('bid',$id)->first();
		//转换时间戳
		$brand->btime = date("Y-m-d H:m:s",$brand->btime);
		//解析模板
		return view('admin.brand.edit',['brand'=>$brand]);
	}

	/*
		执行修改
	*/
	public function postUpdate(Request $request)
	{
		$data = $request->except('_token');
		//判断图片是否上传
		if($request->hasFile('bpic')){
			$data['bpic'] = UserController::upload($request,'bpic','brand');

		}
		$data['btime'] = strtotime($data['btime']);
		$data['updtime'] = time(); 
		//执行添加
		$res = DB::table('shop_brand')->where('bid',$request->input('bid'))->update($data);
		if($res){
			return redirect('/admin/brand/index')->with('success','修改成功');
		}else{
			return back()->with('false','修改失败');
		}
	}

	/*
		品牌状态修改
	*/
	public function postStatus(Request $request)
	{
		
		$id = $request->input('id');
		
		if($request->input('status') == '上架'){
			$data['status'] = '下架';
			$res = DB::table('shop_brand')->where('bid',$id)->update($data);
			echo $res;
		}

		if($request->input('status') == '下架'){
			$data['status'] = '上架';
			$res = DB::table('shop_brand')->where('bid',$id)->update($data);
			echo $res;
		}
	}

}
